#-*- coding:utf-8 -*-
import os
import sys
from datetime import datetime as dt
from ShortMessage import MSG,alert_module_pyMuPDF,alert_file_not_exists,test_file_exists,message_finished
from ArgumentParse import getCropPdfParseResult
from UtilFunction import getMarginRatios
FITZ_IMPORT_FAIL = False
try:
    import fitz 
except:
    FITZ_IMPORT_FAIL =True

def muCropPdfFile(src_file,output_pdf=None,crop_rect_ratio = None):
    output_doc = muCropPdfObject(src_file,crop_rect_ratio)
    if not output_pdf:
        out_put_file = src_file[:-4]+"_crop.pdf"
    else:
        out_put_file = os.path.join(os.getcwd(),output_pdf)
    try:
        output_doc.save(out_put_file)
        MSG("Cropped File   -> %s"%out_put_file)
    except:
        MSG("Write Cropped File Fail")
    message_finished("end")
def muCropPdfObject(pdf_doc,crop_rect_ratio=None):
    if type(pdf_doc) == type(""):
        pdf_doc = fitz.open(pdf_doc)

    output_doc = fitz.open()
    src_rect = pdf_doc.pageCropBox(0)
    crop_rect = None
    if not crop_rect_ratio:
        crop_rect_ratio = (0.1,0.1,0.1,0.1)
    elif type(crop_rect_ratio) == type(""):
        crop_rect_ratio = getMarginRatios(crop_rect_ratio)
    crop_rect = fitz.Rect(src_rect.width * crop_rect_ratio[0],src_rect.height * crop_rect_ratio[1],src_rect.width * (1-crop_rect_ratio[2]),src_rect.height * (1-crop_rect_ratio[3])) 
    MSG("Use CropBox    -> (%.2f,%.2f,%.2f,%.2f)/(%d,%d,%d,%d)"% \
        (crop_rect_ratio[0],crop_rect_ratio[1],crop_rect_ratio[2],crop_rect_ratio[3],crop_rect.x0,crop_rect.y0,crop_rect.x1,crop_rect.y1))
    pg_num = pdf_doc.pageCount
    for i in range(pg_num):
        page = output_doc.newPage(width = src_rect.width,height = src_rect.height)
        page.showPDFpage(src_rect,pdf_doc,i)
        page.setCropBox(crop_rect)
    return pdf_doc
if __name__ == "__main__":
    if FITZ_IMPORT_FAIL:
        alert_module_pyMuPDF()
    else:
        result = getCropPdfParseResult(sys.argv)
        if test_file_exists(result.input_pdf):
            muCropPdfFile(result.input_pdf,result.output_pdf,result.margin_ratios)
